package com.example.sunmiv1.dialog.good;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.sunmiv1.R;
import com.example.sunmiv1.dialog.BaseDialog;
import com.example.sunmiv1.entity.CurrencyInfo;
import com.example.sunmiv1.entity.NewGoodsClassInfo;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class GoodSettingDialog extends BaseDialog {


    @BindView(R.id.goodsSetting_title)
    TextView goodsSettingTitle;
    @BindView(R.id.goodsSetting_off)
    ImageView goodsSettingOff;
    @BindView(R.id.goodsSetting_switch)
    Switch goodsSettingSwitch;
    @BindView(R.id.goodsSetting_switchTv)
    TextView goodsSettingSwitchTv;
    @BindView(R.id.goodsSetting_classList1)
    Spinner goodsSettingClassList1;
    @BindView(R.id.goodsSetting_classList2)
    Spinner goodsSettingClassList2;
    @BindView(R.id.goodsSetting_classList3)
    Spinner goodsSettingClassList3;
    @BindView(R.id.goodsSetting_classLinear)
    LinearLayout goodsSettingClassLinear;
    @BindView(R.id.goodsSetting_tv)
    TextView goodsSettingTv;
    @BindView(R.id.goodsSetting_save)
    TextView goodsSettingSave;
    @BindView(R.id.goodsSetting_delivery1)
    CheckBox goodsSettingDelivery1;
    @BindView(R.id.goodsSetting_delivery2)
    CheckBox goodsSettingDelivery2;
    @BindView(R.id.goodsSetting_delivery3)
    CheckBox goodsSettingDelivery3;
    @BindView(R.id.goodsSetting_deliveryTemplate)
    Spinner goodsSettingDeliveryTemplate;
    @BindView(R.id.goodsSetting_deliveryTemplateLinear)
    LinearLayout goodsSettingDeliveryTemplateLinear;
    @BindView(R.id.goodsSetting_deliveryLinear)
    LinearLayout goodsSettingDeliveryLinear;

    private int type;
    private ACache aCache;
    private Context context;
    private LoadingDialog loadingDialog;
    private ArrayList<String> goodsId;


    private int oneIndex = 0, twoIndex = 0, threeIndex = 0;//選擇的分類的下標
    private NewGoodsClassInfo newGoodsClassInfo;
    private int classType = 0;
    private List<NewGoodsClassInfo.DataBean> oneList = new ArrayList<>();
    private List<NewGoodsClassInfo.DataBean> twoList = new ArrayList<>();
    private List<NewGoodsClassInfo.DataBean> threeList = new ArrayList<>();


    //配送模板
    private CurrencyInfo currencyInfo;
    private int storeFreightIndex = 0;
    private List<CurrencyInfo.DataBean> storeFreightList = new ArrayList<>();

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    break;
                case 2:
                    break;
                case 3:
                    if (classType == 0) {
                        oneList.add(new NewGoodsClassInfo.DataBean("0", "請選擇類別"));
                        oneList.addAll(newGoodsClassInfo.getData());
                        setClass1Adapter();
                    } else if (classType == 1) {
                        if (newGoodsClassInfo.getData().size() > 0) {
                            goodsSettingClassList2.setVisibility(View.VISIBLE);
                        }
                        twoList.add(new NewGoodsClassInfo.DataBean("0", "請選擇類別"));
                        twoList.addAll(newGoodsClassInfo.getData());
                        setClass2Adapter();
                    } else if (classType == 2) {
                        if (newGoodsClassInfo.getData().size() > 0) {
                            goodsSettingClassList3.setVisibility(View.VISIBLE);
                        }
                        threeList.add(new NewGoodsClassInfo.DataBean("0", "請選擇類別"));
                        threeList.addAll(newGoodsClassInfo.getData());
                        setClass3Adapter();
                    }
                    break;
                case 4:
                    break;
            }
        }
    };

    public static GoodSettingDialog newInstance(int type, ArrayList<String> goodsId) {
        GoodSettingDialog fragment = new GoodSettingDialog();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        bundle.putStringArrayList("goodsId", goodsId);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.dialog_good_setting;
    }

    @Override
    protected void initView() {
        context = getContext();
        aCache = ACache.get(getContext());
        loadingDialog = new LoadingDialog(getContext());
    }
    boolean isMore;
    @Override
    public void onResume() {
        super.onResume();
        if (!isMore) {
            isMore = true;
        }else {
            dismiss();
        }
    }

    /**
     *
     */
    @Override
    protected void initData() {
        isMore=false;
        type = getArguments().getInt("type");
        goodsId = getArguments().getStringArrayList("goodsId");
        switch (type) {
            case 1:
                goodsSettingTitle.setText("批次更改-商品類別更改");
                goodsSettingTv.setText("商品類別更改");
                goodsSettingSwitch.setVisibility(View.GONE);
                goodsSettingSwitchTv.setVisibility(View.GONE);
                goodsSettingClassLinear.setVisibility(View.VISIBLE);
                getClassList("");
                break;
            case 2:
                goodsSettingTitle.setText("批次更改-商品上下架");
                goodsSettingSwitchTv.setText("下架");
                goodsSettingTv.setText("商品上下架狀態");
                break;
            case 3:
                goodsSettingTitle.setText("批次更改-店内販售");
                goodsSettingSwitchTv.setText("關");
                goodsSettingTv.setText("店内販售狀態");
                break;
            case 4:
                goodsSettingTitle.setText("批次更改-線上商品販售");
                goodsSettingSwitchTv.setText("關");
                goodsSettingTv.setText("線上商品販售狀態");
                break;
            case 5:
                goodsSettingTitle.setText("批次更改-會員折扣狀態");
                goodsSettingSwitchTv.setText("關");
                goodsSettingTv.setText("店内會員折扣");
                break;
            case 6:
                goodsSettingTitle.setText("批次更改-會員折扣狀態");
                goodsSettingSwitchTv.setText("關");
                goodsSettingTv.setText("線上會員折扣");
                break;
            case 7:
                goodsSettingTitle.setText("批次更改-線上取餐方式");
                goodsSettingTv.setText("線上取餐方式");
                goodsSettingSwitch.setVisibility(View.GONE);
                goodsSettingSwitchTv.setVisibility(View.GONE);
                goodsSettingDeliveryLinear.setVisibility(View.VISIBLE);
                getStoreFreightTem();
                break;
            case 8:
                goodsSettingTitle.setText("批次更改-員工傭金");
                goodsSettingSwitchTv.setText("關");
                goodsSettingTv.setText("員工傭金");
                goodsSettingSave.setText("確認");
                break;
            case 9:
                goodsSettingTitle.setText("批量設置-刪除");
                break;
        }
    }

    @Override
    protected void initListener() {
        goodsSettingSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            switch (type) {
                case 2:
                    goodsSettingSwitchTv.setText("上架");
                    break;
                case 3:
                    goodsSettingSwitchTv.setText("開");
                    break;
                case 4:
                    goodsSettingSwitchTv.setText("開");
                    break;
                case 5:
                    goodsSettingSwitchTv.setText("開");
                    break;
                case 6:
                    goodsSettingSwitchTv.setText("開");
                    break;
                case 8:
                    goodsSettingSwitchTv.setText("開");
                    break;
            }
        });

        goodsSettingClassList1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position != 0) {
                    classType = 1;
                    oneIndex = position;
                    twoIndex = 0;
                    twoList.clear();
                    goodsSettingClassList2.setVisibility(View.INVISIBLE);
                    threeIndex = 0;
                    threeList.clear();
                    goodsSettingClassList3.setVisibility(View.INVISIBLE);
                    getClassList(oneList.get(position).getId());
                } else {
                    twoIndex = 0;
                    twoList.clear();
                    goodsSettingClassList2.setVisibility(View.INVISIBLE);
                    threeIndex = 0;
                    threeList.clear();
                    goodsSettingClassList3.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        goodsSettingClassList2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position != 0) {
                    twoIndex = position;
                    classType = 2;
                    threeIndex = 0;
                    threeList.clear();
                    goodsSettingClassList3.setVisibility(View.INVISIBLE);
                    getClassList(twoList.get(position).getId());
                } else {
                    threeIndex = 0;
                    threeList.clear();
                    goodsSettingClassList3.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        goodsSettingClassList3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                threeIndex = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        goodsSettingDelivery3.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                goodsSettingDeliveryTemplateLinear.setVisibility(View.VISIBLE);
            } else {
                goodsSettingDeliveryTemplateLinear.setVisibility(View.GONE);
            }
        });
        goodsSettingDeliveryTemplate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                storeFreightIndex = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void setClass1Adapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, oneList) {
            @Override
            public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                @SuppressLint("ViewHolder") View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_drop, parent, false);
                final TextView text = view.findViewById(R.id.drop_view);
                text.setText(oneList.get(position).getClass_name());
                return view;
            }

            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_select, parent, false);
                final TextView text = view.findViewById(R.id.spinner_tv);
                text.setText(oneList.get(position).getClass_name());
                return view;
            }
        };
        goodsSettingClassList1.setAdapter(arrayAdapter);
    }

    private void setClass2Adapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, twoList) {
            @Override
            public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                @SuppressLint("ViewHolder") View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_drop, parent, false);
                final TextView text = view.findViewById(R.id.drop_view);
                text.setText(twoList.get(position).getClass_name());
                return view;
            }

            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_select, parent, false);
                final TextView text = view.findViewById(R.id.spinner_tv);
                text.setText(twoList.get(position).getClass_name());
                return view;
            }
        };
        goodsSettingClassList2.setAdapter(arrayAdapter);
    }

    private void setClass3Adapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, threeList) {
            @Override
            public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                @SuppressLint("ViewHolder") View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_drop, parent, false);
                final TextView text = view.findViewById(R.id.drop_view);
                text.setText(threeList.get(position).getClass_name());
                return view;
            }

            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_select, parent, false);
                final TextView text = view.findViewById(R.id.spinner_tv);
                text.setText(threeList.get(position).getClass_name());
                return view;
            }
        };
        goodsSettingClassList3.setAdapter(arrayAdapter);
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            // 下面這些設置必須在此方法(onStart())中才有效
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0xff000000));
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            Window window = dialog.getWindow();
            // 如果不設置這句代碼, 那麼彈框就會與四邊都有一定的距離
            window.setBackgroundDrawableResource(android.R.color.transparent);
            window.setWindowAnimations(R.style.DialogFromBottom);// 設置動畫
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = dm.widthPixels;
            params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
            params.gravity = Gravity.BOTTOM;
            window.setAttributes(setLayout(params));
        }
    }

    @OnClick({R.id.goodsSetting_off, R.id.goodsSetting_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.goodsSetting_off:
                dismiss();
                break;
            case R.id.goodsSetting_save:
                if (type == 1) {
                    if (oneList.size() == 1) {
                        Toast.makeText(context, "請先去後臺添加分類", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (oneList.size() > 1 && oneIndex == 0 || twoList.size() > 1 && twoIndex == 0 || threeList.size() > 1 && threeIndex == 0) {
                        Toast.makeText(context, "請先選擇分類", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                if (type == 7) {
                    if (goodsSettingDelivery3.isChecked() && storeFreightIndex == 0 && storeFreightList.size() > 1) {
                        Toast.makeText(context, "請選擇配送模板", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                batchSetting();
                break;
        }
    }

    /**
     * 獲取商品分類
     */
    private void getClassList(String id) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("pid", id);
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(getContext(), Common.GET_GOODS_CLASS_LIST, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        Message msg = new Message();
                        if (json.getInt("status") == 1) {
                            newGoodsClassInfo = GsonUtils.JsonToBean(text, NewGoodsClassInfo.class);
                            msg.what = 3;
                        } else {
                            msg.what = 4;
                        }
                        handler.sendMessage(msg);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //獲取配送模板
    private void getStoreFreightTem() {
        HttpUtils.post(context, Common.GET_STORE_FREIGHT_TEM, Tools.createParameterCode(new JSONObject()), new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                currencyInfo = GsonUtils.JsonToBean(text, CurrencyInfo.class);
                if (currencyInfo.getStatus() == 1) {
                    storeFreightList.add(new CurrencyInfo.DataBean("0", "請選擇配送模板", "請選擇配送模板", "請選擇配送模板"));
                    storeFreightList.addAll(currencyInfo.getData());
                    ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, storeFreightList) {
                        @Override
                        public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                            @SuppressLint("ViewHolder") View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_drop, parent, false);
                            final TextView text = view.findViewById(R.id.drop_view);
                            text.setText(storeFreightList.get(position).getTitle());
                            return view;
                        }

                        @NonNull
                        @Override
                        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                            View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_select, parent, false);
                            final TextView text = view.findViewById(R.id.spinner_tv);
                            text.setText(storeFreightList.get(position).getTitle());
                            return view;
                        }
                    };
                    goodsSettingDeliveryTemplate.setAdapter(arrayAdapter);
                }
            }

            @Override
            protected void onFailure(ResponseException e) {

            }
        });
    }

    /**
     * 批量操作
     */
    private void batchSetting() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("user_type", aCache.getAsString("userType"));
            JSONArray jsonArray = new JSONArray();
            for (String s : goodsId) {
                jsonArray.put(s);
            }
            jsonObject.put("goodsIds", jsonArray);
            boolean bool = "1".equals(this.aCache.getAsString("userType"));
            if (bool) {
                jsonObject.put("managerType", 3);
            } else {
                jsonObject.put("managerType", 4);
            }
            switch (type) {
                case 1://商品分類
                    jsonObject.put("key", "goods_class_id");
                    String classId = "";
                    if (threeIndex == 0) {
                        if (twoIndex == 0) {
                            if (oneIndex == 0) {
                                Toast.makeText(context, "請先去後臺添加分類", Toast.LENGTH_SHORT).show();
                                return;
                            } else {
                                classId = oneList.get(oneIndex).getId();
                            }
                        } else {
                            classId = twoList.get(twoIndex).getId();
                        }
                    } else {
                        classId = threeList.get(threeIndex).getId();
                    }
                    jsonObject.put("value", classId);
                    break;
                case 2://上下架
                    jsonObject.put("key", "status");
                    jsonObject.put("value", goodsSettingSwitch.isChecked() ? 0 : 1);
                    break;
                case 3://店內出售
                    jsonObject.put("key", "retail_state");
                    jsonObject.put("value", goodsSettingSwitch.isChecked() ? 1 : 0);
                    break;
                case 4://商城出售
                    jsonObject.put("key", "online_state");
                    jsonObject.put("value", goodsSettingSwitch.isChecked() ? 1 : 0);
                    break;
                case 5://會員店內折扣
                    jsonObject.put("key", "vip_retail_state");
                    jsonObject.put("value", goodsSettingSwitch.isChecked() ? 1 : 0);
                    break;
                case 6://會員商城折扣
                    jsonObject.put("key", "vip_online_state");
                    jsonObject.put("value", goodsSettingSwitch.isChecked() ? 1 : 0);
                    break;
                case 7://商城發貨方式
                    JSONArray delivery_type = new JSONArray();
                    if (goodsSettingDelivery1.isChecked()) {
                        delivery_type.put(1);
                    }
                    if (goodsSettingDelivery2.isChecked()) {
                        delivery_type.put(2);
                    }
                    if (goodsSettingDelivery3.isChecked()) {
                        delivery_type.put(3);
                    }
                    jsonObject.put("key", "delivery_type");
                    jsonObject.put("value", delivery_type);
                    if (goodsSettingDelivery3.isChecked()) {
                        jsonObject.put("delivery_template_id", storeFreightList.get(storeFreightIndex).getId());
                    }
                    break;
                case 8://導購推廣
                    jsonObject.put("key", "guide_royalty_state");
                    jsonObject.put("value", goodsSettingSwitch.isChecked() ? 1 : 0);
                    break;
                case 9:

                    break;
            }
            if ("1".equals(aCache.getAsString("userType")) || "2".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(getContext(), Common.BATCH_OPERATE_GOODS, Tools.createParameterCode(jsonObject), new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                loadingDialog.dismiss();
                try {
                    JSONObject json = new JSONObject(text);
                    Toast.makeText(getContext(), json.getString("message"), Toast.LENGTH_SHORT).show();
                    if (json.getInt("status") == 1) {
                        callback.success("");
                        dismiss();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
            }
        });

    }

}
